<template>
  <Content :title="id ? '编辑工单' : '申请维修'">
    <view
      class="from-box"
      :style="{ 'padding-bottom': type == 'details' ? '40rpx' : '160rpx' }"
    >
      <view class="content content-bottom">
        <u-form
          labelPosition="left"
          :model="model"
          labelWidth="80"
          labelAlign="left"
          :rules="rules"
          ref="uForm"
        >
          <u-form-item
            :borderBottom="type == 'edit'"
            label="选择班组"
            required
            prop="team"
          >
            <uni-data-select
              v-model="model.team"
              :localdata="teamList"
              @change="teamChange"
              placeholder="请选择"
            ></uni-data-select>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="选择班次"
            required
            prop="shift"
          >
            <uni-data-select
              v-model="model.shift"
              :localdata="shiftList"
              placeholder="请选择"
            ></uni-data-select>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="模具编号"
            required
            prop="moldCode"
          >
            <uni-data-select
              v-model="model.moldCode"
              :localdata="moldInfoList"
              showInput
              @inputChange="getMoldInfo"
              placeholder="请选择"
              @change="getMoldInfoChange"
            ></uni-data-select>
          </u-form-item>

          <!-- 1 -->
          <u-form-item
            :borderBottom="type == 'edit'"
            label="模具名称"
            prop="moldName"
          >
            <u-input
              label
              readonly
              v-model="model.moldName"
              placeholder="请填写模具名称"
            ></u-input>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="是否验收"
            required
            prop="maintenanceStatus"
          >
            <uni-data-select
              v-model="model.maintenanceStatus"
              :localdata="maintenances"
              placeholder="请选择"
            ></uni-data-select>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="报修人"
            prop="repairApplicant"
          >
            <u-input
              label
              v-model="model.repairApplicant"
              placeholder="请填写报修人"
              clearable
            ></u-input>
          </u-form-item>

          <!-- 1 -->
          <u-form-item
            :borderBottom="type == 'edit'"
            label="报修电话"
            prop="repairHotline"
          >
            <u-input
              v-model="model.repairHotline"
              placeholder="请填写报修电话"
              type="number"
              clearable
            ></u-input>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="模具所在设备编号"
            prop="punchNumber"
			required
          >
		  <uni-data-select
		    v-model="model.punchNumber"
		    :localdata="deviceInfoList"
		    showInput
		    @inputChange="getDeviceInfo"
		    placeholder="请选择"
		    @change="getDeviceChange"
		  ></uni-data-select>
         <!--   <u-input
              label
              v-model="model.punchNumber"
              placeholder="请填写模具所在设备编号"
              clearable
            ></u-input> -->
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="压机编号"
            prop="pressNumber"
          >
            <u-input
              label
              v-model="model.pressNumber"
              placeholder="请填写压机编号"
              clearable
            ></u-input>
          </u-form-item>
          <!-- 1 -->
          <u-form-item
            :borderBottom="type == 'edit'"
            label="焊机编号"
            prop="weldingMachineNumber"
          >
            <u-input
              label
              v-model="model.weldingMachineNumber"
              placeholder="请填写焊机编号"
              clearable
            ></u-input>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="冲压材料"
            prop="stampingMaterials"
          >
            <u-input
              label
              v-model="model.stampingMaterials"
              placeholder="请填写冲压材料"
              clearable
            ></u-input>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="冲压用油"
            prop="stamping"
          >
            <!-- <u-input
              label
              v-model="model.stamping"
              placeholder="请填写冲压用油"
              clearable
            ></u-input> -->
          <uni-data-select
            v-model="model.stamping"
            :localdata="stampingList"
            placeholder="请选择冲压用油"
          ></uni-data-select>
          </u-form-item>
          <!-- 1 -->
          <u-form-item
            :borderBottom="type == 'edit'"
            label="异常现象"
            prop="abnormalPhenomena"
            required
          >
            <uni-data-picker
              v-model="model.abnormalPhenomena"
              :localdata="abnormalList"
              :map="{ text: 'label', value: 'value' }"
              popup-title="请选择"
            ></uni-data-picker>
          </u-form-item>
          <!-- 1 -->
          <u-form-item
            :borderBottom="type == 'edit'"
            label="紧急程度"
            prop="urgencyLevel"
            required
          >
            <uni-data-select
              v-model="model.urgencyLevel"
              :localdata="originIncidents"
              placeholder="请选择"
            ></uni-data-select>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="故障时间"
            prop="faultTime"
            required
          >
            <MyDate
              mode="datetime"
              v-model="model.faultTime"
              placeholder="请选择"
            ></MyDate>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="模具（产品）异常情况描述"
            prop="exceptionDescription"
          >
            <u-textarea
              v-model="model.exceptionDescription"
              placeholder="请填写模具（产品）异常情况描述"
              count
            ></u-textarea>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="是否附样"
            prop="sampleAttached"
          >
            <u-radio-group v-model="model.sampleAttached" placement="row">
              <u-radio label="是" name="1" style="margin-right: 20px"></u-radio>
              <u-radio label="否" name="2"></u-radio>
            </u-radio-group>
          </u-form-item>

          <u-form-item
            :borderBottom="type == 'edit'"
            label="上传附件"
            prop="uploadAttachments"
          >
          <!-- <MyUpload
              v-model="fileList"
              @click.native="open"
			  @change="fileChange"
              multiple
			  ref="myUploaderFiles"
              :maxCount="5"
            ></MyUpload> -->
          <MyUploaderFiles
			  v-model="fileList"
              ref="myUploaderFiles"
              @click.native="open"
			  @change="fileChange"
            ></MyUploaderFiles>
          </u-form-item>

          <!-- <MyUpload
              v-model="fileList"
              accept="image/*,video/*"
              multiple
              :maxCount="5"
            ></MyUpload> -->

          <view class="btn-v" v-if="type != 'details'">
            <view class="but-box">
              <u-button class="btn" text="取消" @click="close"></u-button>
              <u-button
                class="btn"
                type="primary"
                @click="submit"
                text="确认提交"
              ></u-button>
            </view>
          </view>
        </u-form>
      </view>
    </view>
  </Content>
</template>

<script>
import Content from "@/components/content/index.vue";
import MyDate from "@/components/myDate.vue";
import { getPageData, getUserInfo } from "@/store/user";
import fetch from "@/utils/fetch";
import { getMoldInfoList } from "@/api/moldManagement/moldInApply.js";
import MyUpload from "@/components/myUpload";
import MyUploaderFiles from "@/components/MyUploaderFiles";
import { getAbnormalPhenomenaList } from "@/api/moldManagement/abnormalPhenomenaList.js";
export default {
  props: {
    pageType: {
      type: String,
      default: "warehousing",
    },
    type: {
      type: String,
      default: "edit",
    },
  },
  options: {
    multipleSlots: true,
  },
  components: {
    Content,
    MyDate,
    MyUpload,
    MyUploaderFiles,
  },
  data() {
    return {
      shipData: {},
      showDate: false,
      showDate1: false,
	  stampingList:[],
      newDate: Number(new Date()),
      moldInfoList: [],
      deviceInfoList: [],
      userInfo: {},
      model: {
        maintenanceStatus: "",
        team: "",
        shift: "",
        repairApplicant: "",
        repairHotline: "",
        moldCode: "",
        moldName: "",
        moldGrade: "",
        acceptanceStatus: "",
        punchNumber: "",
        pressNumber: "",
        stampingMaterials: "",
        stamping: "",
        abnormalPhenomena: [],
        urgencyLevel: "",
        faultTime: "",
        exceptionDescription: "",
        uploadAttachments: "",
        sampleAttached: "",
      },
      rules: {
        team: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        shift: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        team: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        maintenanceStatus: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
		punchNumber: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        urgencyLevel: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        faultTime: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        abnormalPhenomena: {
          type: "array",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
        repairHotline: [
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return value ? uni.$u.test.mobile(value) : true;
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        moldCode: {
          type: "string",
          required: true,
          message: "请填写",
          trigger: ["change", "blur"],
        },
      },
      originIncidents: [
        { text: "特急", value: "1" },
        { text: "紧急", value: "2" },
        { text: "一般", value: "3" },
      ],
      maintenances: [
        { text: "新模", value: "0" },
        { text: "常规模", value: "1" },
      ],
      data: [],
      titleBarHeight: 0,
      fileList: [],
      teamList: [],
      shiftList: [],
      deviceTzList: [],
      target: "",
	  abnormalList:getAbnormalPhenomenaList(),
      id: "",
    };
  },
  onLoad: function (option) {
    //option为object类型，会序列化上个页面传递的参数
    const that = this;
	this.getStampingList();
    that.userInfo = getUserInfo();
    that.model.repairApplicant = that.userInfo.realname;
    that.model.repairHotline = that.userInfo.phone;
    that.model.faultTime = that
      .$dayjs(new Date())
      .format("YYYY-MM-DD HH:mm:ss");

    if (option.id) {
      that.id = option.id;
      const formTop = getPageData();
	  console.log(formTop,'formTop')
      that.model = {
        ...formTop,
        username:
          formTop.maintainApplyByEmpno + "-" + formTop.maintainApplyByStr,
        faultTime: formTop.faultTime,
        maintainApplyDate: formTop.maintainApplyDate,
        abnormalPhenomena: formTop.abnormalPhenomena.split(","),
        faultMessage: formTop.faultMessage ? formTop.faultMessage : "无",
      };
      that.fileList = formTop.uploadAttachments.map((item) => {
        return {
          ...item,
          url: item.fileUrl,
        };
      });
	  // that.$refs.MyUploaderFiles.imageList=that.fileList
      that.teamChange(formTop.team, true);
      console.log("that.model", that.model);
      that.getMoldInfo(formTop.moldCode);
    }
  },
  onReady: function () {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    if (this.$refs.uForm) this.$refs.uForm.setRules(this.rules);
    this.getTeamList();
  },
  methods: {
    open() {
      this.$refs.myUploaderFiles.chooseVideoImage();
    },
    onchange(e) {
      const value = e.detail.value;
    },
	fileChange(val){
		const data=val.map(item=>{
			return {
				filePath:item.filepath,
				...item
			}
		})
		this.fileList.push(...data)
	},
    onnodeclick(node) {},
    async dateChange(val, type) {
      if (type === "leaveDate") {
        this.showDate1 = false;
      } else {
        this.showDate = false;
      }
      const timeFormat = uni.$u.timeFormat;
      let timeValue = await timeFormat(val.value, "yyyy-mm-dd hh:MM");
      this.model[type] = timeValue;
    },
    getMoldInfo(query) {
      if (!query) return;
      return fetch("post", "/dms/moldOutbound/getMoldInfoList", {
        moldCode: query,
        pageSize: 25,
        pageNum: 1,
      }).then(({ data }) => {
        this.moldInfoList =
          data.records?.map((item) => {
            return {
              ...item,
              text: item.moldCode,
              value: item.moldCode,
            };
          }) || [];
      });
    },
    getMoldInfoChange(params) {
      if (!!!params) {
        this.model.moldName = "";
        return;
      }
      console.log("params", params);
      this.model.moldName =
        this.moldInfoList.find((item) => item.moldCode == params).moldName ||
        "";
    },
	getDeviceInfo(query) {
      if (!query) return;
      return fetch("post", "/dms/device/page", {
        deviceNo: query,
        pageSize: 25,
        pageNum: 1,
      }).then(({ data }) => {
        this.deviceInfoList =
          data.records?.map((item) => {
            return {
              ...item,
              text: item.deviceNo+'--'+item.deviceName,
              value: item.deviceNo,
            };
          }) || [];
      });
    },
    getDeviceInfoChange(params) {
      if (!!!params) {
        this.model.deviceNo = "";
        return;
      }
      this.model.punchNumber =
        this.deviceInfoList.find((item) => item.deviceNo == params).deviceNo ||
        "";
    },
    //班组变化是
    teamChange(val, bon) {
      this.model.team = val;
      if (!bon) this.$set(this.model, "shift", "");
      fetch("get", "/dms/productionShift/selectByTeam", {
        teamName: val,
      }).then((res) => {
        this.shiftList = res.data.map((item) => ({
          value: item.shift,
          text: item.shift,
        }));
      });
    },
    //班组列表
    getTeamList() {
      fetch("get", "/dms/productionTeam/selectTeamByUser").then((res) => {
        this.teamList = res.data.map((item) => ({
          value: item.team,
          text: item.team,
        }));
      });
    },
	getStampingList() {
      fetch("get", "/dms/faultCategory/dictList?name=冲压用油").then((res) => {
        this.stampingList = res.data.map((item) => ({
          value: item.value,
          text: item.value,
        }));
      });
    },
    close() {
      uni.navigateBack({
        delta: 1,
      });
    },
    approve(bon) {
      fetch("post", "/jeecg-boot/miniprogram/approve", {
        applyId: this.model.id,
        approve: bon,
        comment: this.model.approveComment,
      }).then((data) => {
        uni.$emit("openToast", {
          type: "success",
          title: "完成审批",
          complete() {
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1000);
          },
        });
      });
    },
    submit() {
      const that = this;
	  console.log(that.fileList)
	  const paramsData={
	      ...that.model,
	      abnormalPhenomena: that.model.abnormalPhenomena.join(","),
	      uploadAttachments: that.fileList.map((item) => {
	        return {
	          ...item,
	          fileName: item.fileName,
	          filePath: item.filePath,
	          fileUrl: item.fileUrl,
	        };
	      }),
	    };
	  console.log(JSON.stringify(paramsData),'paramsData')
      that.$refs.uForm.validate().then((valid) => {
        if (valid) {
          that.$loading.open();
          console.log("that.model", that.model, that.model.abnormalPhenomena);
          let url = !that.id
            ? "/dms/moldMaintenanceHall/add"
            : "/dms/moldMaintenanceHall/update";
	
          fetch("post", url, {
            ...that.model,
            abnormalPhenomena: that.model.abnormalPhenomena.join(","),
            uploadAttachments: that.fileList.map((item) => {
              return {
                ...item,
				 fileName: item.fileName,
				 filePath: item.filePath,
				 fileUrl: item.fileUrl,
              };
            }),
          }).then((data) => {
            uni.$emit("openToast", {
              type: "success",
              title: "申请成功",
              complete() {
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1,
                  });
                }, 1000);
              },
            });
          });
        } else {
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.from-box {
  padding: 20rpx;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;

  /deep/ .u-form-item__body__left__content__label {
    margin-left: 20rpx;
  }

  // /deep/ .uni-select {
  //     border: none;
  //     border-bottom: none;
  //     line-height: 26px;
  //     height: 24px !important;
  //     padding-left: 0;
  // }

  /deep/ .uni-select__input-placeholder {
    color: #cbc9cc !important;
    font-size: 15px !important;
  }
}

.content {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 12rpx 18rpx -6rpx rgba(0, 0, 0, 0.2);
}

.content-bottom {
  flex: 1;
}
</style>
